package com.jilian.mydemo.modul.order.ui;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.common.dto.OrderDto;
import com.jilian.mydemo.modul.order.viewmodel.OrderViewModel;
import com.jilian.mydemo.utils.DateUtil;
import com.jilian.mydemo.utils.EmptyUtils;
import com.jilian.mydemo.utils.ToastUitl;

import java.util.Calendar;
import java.util.Date;

/**
 * 填写预约信息
 */
public class FillReservationInformationActivity extends BaseActivity {
    private TextView tvNumber;
    private TextView tvType;
    private TextView tvName;
    private TextView tvDate;
    private TextView tvAdress;
    private RelativeLayout rlStartTime;
    private TextView tvStartTime;
    private RelativeLayout rlStopTime;
    private TextView tvStopTime;
    private EditText etContent;
    private TextView tvOk;
    TimePickerView pvCustomTime;
    private OrderViewModel orderViewModel;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }


    @Override
    protected void createViewModel() {
        orderViewModel = ViewModelProviders.of(this).get(OrderViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_fillreservationinformation;
    }

    @Override
    public void initView() {
        setNormalTitle("填写预约信息", v -> finish());
        tvNumber = (TextView) findViewById(R.id.tv_number);
        tvType = (TextView) findViewById(R.id.tv_type);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvDate = (TextView) findViewById(R.id.tv_date);
        tvAdress = (TextView) findViewById(R.id.tv_adress);
        rlStartTime = (RelativeLayout) findViewById(R.id.rl_start_time);
        tvStartTime = (TextView) findViewById(R.id.tv_start_time);
        rlStopTime = (RelativeLayout) findViewById(R.id.rl_stop_time);
        tvStopTime = (TextView) findViewById(R.id.tv_stop_time);
        etContent = (EditText) findViewById(R.id.et_content);
        tvOk = (TextView) findViewById(R.id.tv_ok);
        initCustomTimePicker();
    }
   private  OrderDto orderDto;
    @Override
    public void initData() {
         orderDto = (OrderDto) getIntent().getSerializableExtra("order");
        if(EmptyUtils.isNotEmpty(orderDto)){
            tvNumber.setText(orderDto.getOrderNo());
            tvType.setText(orderDto.getServiceType());
            tvName.setText(orderDto.getCustomerName());
            tvDate.setText(orderDto.getBookTime());
            tvAdress.setText(orderDto.getServiceAddress());
            tvStartTime.setText(orderDto.getBookTime());
            tvStopTime.setText(orderDto.getBookEndTime());
        }

    }

    @Override
    public void initListener() {
        rlStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dateType = 1;
                pvCustomTime.show();
            }
        });
        rlStopTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dateType = 2;
                pvCustomTime.show();
            }
        });
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(stopDateTime>0&&startDateTime>0&&stopDateTime<=startDateTime){
                    ToastUitl.showImageToastTips("截止时间要大于开始时间");
                    return;
                }
                subscribe();
            }
        });
    }

    /**
     * 预约
     */
    private void subscribe() {
        showLoadingDialog();
        orderViewModel.subscribe(orderDto.getId(),tvStartTime.getText().toString(),tvStopTime.getText().toString(),etContent.getText().toString());
        orderViewModel.getSubscribeliveData().observe(this, new Observer<BaseDto>() {
            @Override
            public void onChanged(@Nullable BaseDto dto) {
                hideLoadingDialog();
                if(dto.isSuccess()){
                    ToastUitl.showImageToastSuccess(dto.getMsg());
                    finish();
                    MyApplication.clearSpecifyActivities(new Class[]{TwoOrderDetailActivity.class});
                }
                else{
                    ToastUitl.showImageToastTips(dto.getMsg());
                }
            }
        });
    }

    private int dateType ;//1 开始时间 2 结束时间 3 预约时间
    private long startDateTime;
    private long stopDateTime ;

    /**
     * 初始化时间数据
     */
    private void initCustomTimePicker() {
        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(1918, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2029,01,01);
        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if(dateType==1){
                    tvStartTime.setText(DateUtil.dateToString(DateUtil.DEFAULT_DATE_FORMATTER_HOUR, date)+":00");
                    startDateTime = date.getTime();
                }
                if(dateType==2){
                    tvStopTime.setText(DateUtil.dateToString(DateUtil.DEFAULT_DATE_FORMATTER_HOUR, date)+":00");
                    stopDateTime = date.getTime();
                }
                initButtonEnable();

            }
        })
                /*.setType(TimePickerView.Type.ALL)//default is all
                .setCancelText("Cancel")
                .setSubmitText("Sure")
                .setContentTextSize(18)
                .setTitleSize(20)
                .setTitleText("Title")
                .setTitleColor(Color.BLACK)
               /*.setDividerColor(Color.WHITE)//设置分割线的颜色
                .setTextColorCenter(Color.LTGRAY)//设置选中项的颜色
                .setLineSpacingMultiplier(1.6f)//设置两横线之间的间隔倍数
                .setTitleBgColor(Color.DKGRAY)//标题背景颜色 Night mode
                .setBgColor(Color.BLACK)//滚轮背景颜色 Night mode
                .setSubmitColor(Color.WHITE)
                .setCancelColor(Color.WHITE)*/
                /*.animGravity(Gravity.RIGHT)// default is center*/
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        final TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                                pvCustomTime.dismiss();
                            }
                        });
                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
                .setContentTextSize(18)
                //各个部分是否显示
                .setType(new boolean[]{true, true, true, true, false, false})
                //时间格式
                .setLabel("", "", "", ":00", "分", "秒")
                .setLineSpacingMultiplier(1.2f)
                .setTextXOffset(40, 0, -40, 0, 0, -0)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFFe0e0e0)
                .setLineSpacingMultiplier(2f)
                .build();
    }

    /**
     * 设置按钮是否可用
     */
    private void initButtonEnable() {
        if(TextUtils.isEmpty(tvStartTime.getText().toString())||TextUtils.isEmpty(tvStopTime.getText().toString())){
            tvOk.setBackgroundResource(R.drawable.shape_btn_login_dark);
            tvOk.setEnabled(false);
        }
        else{
            tvOk.setBackgroundResource(R.drawable.shape_btn_login_normal);
            tvOk.setEnabled(true);
        }
    }
}
